import xbmc, xbmcgui, xbmcaddon, xbmcplugin
from BeautifulSoup import BeautifulSoup, SoupStrainer,BeautifulSOAP
import urllib, urllib2
import re, string, sys, os,traceback
import urlresolver
from t0mm0.common.addon import Addon
from t0mm0.common.net import Net
import unicodedata
from time import sleep

playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
addon_id = 'plugin.video.tamiletv3'
xaddon = xbmcaddon.Addon(id=addon_id)
addon = Addon(addon_id, sys.argv)
seperator = ":;"
lineseperator = ":~"
net = Net()
showAllParts = True
showPlayAll = True

AddonPath = xaddon.getAddonInfo('path')
ResourcesPath = AddonPath + "/resources/"
IconPath = AddonPath + "/icons/"



if xaddon.getSetting('showAllParts') == 'false':
        showAllParts = False

if xaddon.getSetting('showPlayAll') == 'false':
        showPlayAll = False

################### Global Constants #################################
MainUrl = 'http://www.rajtamil.com/'
MovieUrl = MainUrl + "category/2012/"
VijayTVUrl = MainUrl + "category/vijay-tv-shows/"
SunTVUrl = MainUrl + "category/sun-tv-show/"
ThangamUrl = MainUrl + "category/sun-tv-serials/thangam/"
thirumathiselvamnUrl = MainUrl + "category/sun-tv-serials/thirumathi-selvam/"
ThendralUrl = MainUrl + "category/sun-tv-serials/thendral/"


##### Queries ##########
play = addon.queries.get('play', None)
mode = addon.queries['mode']
url = addon.queries.get('url', None)
content = addon.queries.get('content', None)
query = addon.queries.get('query', None)
startPage = addon.queries.get('startPage', None)
numOfPages = addon.queries.get('numOfPages', None)
listitem = addon.queries.get('listitem', None)
urlList = addon.queries.get('urlList', None)


print 'Mode: ' + str(mode)
print 'URL: ' + str(url)
print 'urlList: ' + str(urlList)
print 'query: ' + str(query)
print 'Play: ' + str(play)
print 'content: ' + str(content)


def removedup(seq):
    seen = set()
    seen_add = seen.add
    return [ x for x in seq if x not in seen and not seen_add(x)]


def unescape(url):
        htmlCodes = [
                ['&', '&amp;'],
                ['<', '&lt;'],
                ['>', '&gt;'],
                ['"', '&quot;'],
        ]
        for code in htmlCodes:
                url = url.replace(code[1], code[0])
        return url


def getVideoTitle(video):
        return getText(video.getElementsByTagName("title")[0].childNodes)
        
def getVideoID(video):
        return getText(video.getElementsByTagName("yt:videoid")[0].childNodes)
                
def getText(nodelist):
        rc = []
        for node in nodelist:
                if node.nodeType == node.TEXT_NODE:
                        rc.append(node.data)
        return ''.join(rc)
    
def retreiveYouTubePlayList(playlistID):
    try:
        url='http://gdata.youtube.com/feeds/api/playlists/'+playlistID+'?v=2'
        link=net.http_GET(url).content
        domObj = parseString(link)
        #print domObj.toprettyxml()
        videos=domObj.getElementsByTagName("entry")
        return videos
    except:
        traceback.print_exc()
        return []


def getXML():
        try:
            return open( os.path.join( ResourcesPath, "snappers.xml")).read()
        except:
            traceback.print_exc()
        return ""
    
def get_match(data, regex) :
    match = "";
    m = re.search(regex, data)
    if m != None :
        match = m.group(1)
    return match

def GetTitles(url, startPage= '1', numOfPages= '1'): # Get Movie Titles
        print 'Rajtamil get Titles Menu %s' % url

        # handle paging
        
        html = net.http_GET(url).content

        match = re.compile('<div class="cover"><a href="(.+?)".+?title="(.+?)".+?<img src="(.+?)"').findall(html)
    
        for link,movie,img in match:
            movie = movie.encode('ascii', 'ignore')
            addon.add_directory({'mode': 'GetLinks', 'url': link}, {'title': movie},img=img)
        xbmcplugin.endOfDirectory(int(sys.argv[1]))


    
    
    
    
def GetLinks(url): # Get Links
        print '***************************************************** In GetLinks %s' % url
        html = net.http_GET(url).content
        listitem = GetMediaInfo(html)
        medias=""
        #DailMotion Video
        try:
            print "############################ Trying DailyMotion ############################"
            soupStrainer  = SoupStrainer("snapper", {"module": "snapvideo.Dailymotion","function":"retrieveVideoInfo"})
            soup = BeautifulSoup(SNAPXML,parseOnlyThese=soupStrainer)
            videoid = soup.findAll("video-id")
            for video in videoid:
                print "Trying:"+video['regex']
                p = re.compile(video['regex'])
                match = p.findall(html)
                count=0
                match=removedup(match)
                for link in match:
                    print "Match:"+link
                    count=count+1
                    titlename="dailymotion"+str(count)
                    media = 'dailymotion'+seperator+link+seperator+titlename
                    medias=medias+lineseperator+media
                    addon.add_video_item({'mode': 'PlayVideo','url':media, 'listitem': listitem}, {'title': titlename})
                if match : break
        except:
            pass


        #Youtube DailyMotion Playlist
        try:
            print "############################ Trying Dailymotion Playlist ############################"
            soupStrainer  = SoupStrainer("snapper", {"module": "snapvideo.Dailymotion","function":"retrievePlaylistVideoItems"})
            soup = BeautifulSoup(SNAPXML,parseOnlyThese=soupStrainer)
            videoid = soup.findAll("video-id")
            for video in videoid:
                print "Trying:"+video['regex']
                p = re.compile(video['regex'])
                match = p.findall(html)
                count=0
                match=removedup(match)
                if match :
                    playlistID=match[0]
                    print "Match:"+playlistID
                    dplaylist = net.http_GET('http://www.dailymotion.com/playlist/' + playlistID).content
                    dplaylist = ''.join(dplaylist.splitlines()).replace('\t', '')
                    videoList = re.compile('video_item.+?data-id="(.+?)"').findall(dplaylist)
                    
                    i = 1
                    playList = ''
                    matchCount = len(videoList)
                    if(matchCount == 1):
                        media = 'dailymotion'+seperator+videoList[0][1]+seperator+"dailyMotion"
                        medias=medias+lineseperator+media
                        addon.add_video_item({'mode': 'PlayVideo','url':media, 'listitem': listitem}, {'title': titlename})
                    elif(matchCount > 1):
                        for videoid in videoList:
                            print "Dailymotion Video ID:"+videoid
                            count=count+1
                            titlename="dailymotion"+str(count)
                            media = "dailymotion"+seperator+videoid+seperator+titlename
                            medias=medias+lineseperator+media
                            addon.add_video_item({'mode': 'PlayVideo','url':media, 'listitem': listitem}, {'title': titlename})
                    if matchCount!=0: break
                        
                        
                    
        except:
            traceback.print_exc()
            pass
        
        #Youtube Video
        try:
            print "############################ Trying Youtube ############################"
            soupStrainer  = SoupStrainer("snapper", {"module": "snapvideo.YouTube","function":"retrieveVideoInfo"})
            soup = BeautifulSoup(SNAPXML,parseOnlyThese=soupStrainer)
            videoid = soup.findAll("video-id")
            for video in videoid:
                print "Trying:"+video['regex']
                p = re.compile(video['regex'])
                match = p.findall(html)
                count=0
                match=removedup(match)
                for link in match:
                    count=count+1
                    titlename="youtube"+str(count)
                    media = "youtube"+seperator+link+seperator+titlename
                    medias=medias+lineseperator+media
                    addon.add_video_item({'mode': 'PlayVideo','url':media, 'listitem': listitem}, {'title': titlename})
                if match : break
                    
        except:
            pass

        #Youtube Video Playlist
        try:
            print "############################ Trying Youtube Playlist ############################"
            soupStrainer  = SoupStrainer("snapper", {"module": "snapvideo.YouTube","function":"retrievePlaylistVideoItems"})
            soup = BeautifulSoup(SNAPXML,parseOnlyThese=soupStrainer)
            videoid = soup.findAll("video-id")
            for video in videoid:
                print "Trying:"+video['regex']
                p = re.compile(video['regex'])
                match = p.findall(html)
                count=0
                match=removedup(match)
                if match :
                    print "Match:"+match[0]
                    videos = retreiveYouTubePlayList(match[0])
                    for video in videos:
                        print "############################################"+getVideoTitle(video)
                        count=count+1
                        titlename="youtube"+str(count)+ " " +getVideoTitle(video)
                        media = "youtube"+seperator+getVideoID(video)+seperator+titlename
                        medias=medias+lineseperator+media
                        addon.add_video_item({'mode': 'PlayVideo','url':media, 'listitem': listitem}, {'title': titlename})
                    if len(videos)!=0: break
                        
                        
                    
        except:
            traceback.print_exc()
            pass

    
        try:
            p = re.compile("http://www.sockshare.com/embed/(\w+)")
            match = p.findall(html)
            print "Sockshare - Video"
            print match
            print match[0]    
            media = "sockshare"+seperator+match[0]+seperator+"sockshare"
            medias=medias+lineseperator+media
            addon.add_video_item({'mode': 'PlayVideo','url':media, 'listitem': listitem}, {'title': 'sockshare'})
        except:
            pass
        
        try:
            p = re.compile("http://embed.nowvideo.eu/embed.php\?v=(\w+)")
            match = p.findall(html)
            print "Nowvideo - Video"
            if match:
                print match[0]    
                data = net.http_GET("http://embed.nowvideo.eu/embed.php?v="+match[0]).content
                afile = get_match(data,'flashvars.file="([^"]+)"')
                key = get_match(data,'flashvars.filekey="([^"]+)"')
                codes = get_match(data,'flashvars.cid="([^"]+)"')
                url = "http://www.nowvideo.eu/api/player.api.php?file="+afile+"&user=undefined&codes="+codes+"&pass=undefined&key="+key.replace(".","%2E").replace("-","%2D")
                data = net.http_GET(url).content
                location = get_match(data,'url=([^\&]+)&')
                location = location + "?client=FLASH"

                if not location:
                        location = 'CONTENTREMOVED'
                print ('auth url is ' + str(location))
                medias=medias+lineseperator+str(location)
                addon.add_video_item({'url': str(location), 'mode': 'PlayVideo', 'video': "Now Video"}, {'title': "NowVideo"})
        except:
            traceback.print_exc()
            pass
        
        
        
        addon.add_video_item({'mode': 'PlayVideoList', 'url':medias, 'listitem': listitem}, {'title': "Play All Videos" })
            
        xbmcplugin.endOfDirectory(int(sys.argv[1]))

def SortUrlList(urlList):
        print 'In SortUrlList'
        retList = [''] * len(urlList)
        for url in urlList:
                partNum = re.search('\.[0]+([\d]+)[\.]*[(?:html|htm)]*', url, re.IGNORECASE).group(1)
                retList[int(partNum) - 1] = url
        print retList
        return retList

def GetVideoLinks(host, url):
        if any(host in s for s in SITES_1):
                links = re.compile('iframe.+?src="(.+?)"', re.IGNORECASE).findall(net.http_GET(url).content)
                if len(links):
                        return links[0]
        if any(host in s for s in SITES_2):
                links = re.compile('object.+?src="(.+?)"').findall(net.http_GET(url).content)
                if len(links):
                        return links[0]
        #print 'ignored tamilwire url %s' % url
        return url

def PlayVideo(url):
    print '************************************* in PlayVideo'
    print "url is %s" % url
    try:
        #addon.resolve_url(url)
        xbmc.Player().play(url)
    except:
        traceback.print_exc()
        print 'error while trying to PlayVideo'
            
def PlayVideoList(url,listitem):
    print '************************************* in Play Video List '
    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    playlist.clear()
    lines = url.split(lineseperator)
    for line in lines:
        m=line.split(seperator)
        if(len(m)>1):
            print "M0 "+m[0]+" M1 "+m[1]+" M2 "+m[2]
            media=urlresolver.HostedMediaFile(host=m[0], media_id=m[1], title=m[2])
            if media:
                liz = xbmcgui.ListItem(m[2], thumbnailImage="")
                playlist.add(url=media.resolve(),listitem=liz)
        else:
            playlist.add(line)
    xbmc.Player().play(playlist)
    if not xbmc.Player().isPlayingVideo():
                d = xbmcgui.Dialog()
                d.ok('VIDEO QUEUE EMPTY', 'The XBMC video queue is empty.', 'Add more links to video queue.')
    '''cnt=0
    #urlList = unicodedata.normalize('NFKD', urlList).encode('ascii','ignore')
    urlList = map(str, urlList[1:-1].split(','))
    #print "URLList is "+urlList
    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    playlist.clear()
    for url in urlList:
        cnt=cnt+1
        #url = unicodedata.normalize('NFKD', url).encode('ascii','ignore')
        url = url.replace('\\r', '').replace("u'", "").replace("'", "").strip()
        print "URL:"+url
        liz=xbmcgui.ListItem("title"+str(cnt), iconImage="DefaultFolder.png")
        liz.setInfo("Video", { "Title": "title"+str(cnt)} )
        playlist.add(url=url,listitem=liz)
    xbmc.Player().play(playlist)
    #xbmc.executebuiltin('playlist.playoffset(video,0)')
    #if not xbmcPlayer.isPlayingVideo():
    #    d = xbmcgui.Dialog()
    #    d.ok('VIDEO QUEUE EMPTY', 'The XBMC video queue is empty.','Add more links to video queue.')'''
    
        

def GetDomain(url):
        tmp = re.compile('//(.+?)/').findall(url)
        domain = 'Unknown'
        if len(tmp) > 0 :
            domain = tmp[0].replace('www.', '')
        return domain


def GetMediaInfo(html):
        listitem = xbmcgui.ListItem()
        match = re.search('<title>(.+?)</title>', html)
        if match:
            listitem.setInfo( type="video", infoLabels={ "Title":  match.group(1)} )
        return listitem

def MainMenu():  #homescreen
        addon.add_directory({'mode': 'GetTitles', 'url':MovieUrl,'section': 'movies'}, {'title':  'RajTamil Movies'})
        addon.add_directory({'mode': 'GetHDTitles', 'url':'http://www.einthusan.com/movies/index.php?lang=tamil&organize=Activity&filtered=RecentlyPosted&org_type=Activity','section': 'movies'}, {'title': 'Einthusan Recent Tamil Movies'})
        addon.add_directory({'mode': 'GetHDTitles', 'url':'http://www.einthusan.com/movies/index.php?lang=hindi&organize=Activity&filtered=RecentlyPosted&org_type=Activity','section': 'movies'}, {'title': 'Einthusan Recent Hindi Movies'})
        addon.add_directory({'mode': 'GetHDTitles', 'url':'http://www.einthusan.com/movies/index.php?lang=tamil&organize=Statistics&filtered=ThisWeekViews&org_type=Statistics','section': 'movies'}, {'title': 'Einthusan MostViewed Tamil Movies'})
        addon.add_directory({'mode': 'GetHDTitles', 'url':'http://www.einthusan.com/movies/index.php?lang=hindi&organize=Statistics&filtered=ThisWeekViews&org_type=Statistics','section': 'movies'}, {'title': 'Einthusan MostViewed Hindi Movies'})
        addon.add_directory({'mode': 'GetTitles', 'url':VijayTVUrl,'section': 'tv'}, {'title': 'Vijay TV Shows'})
        addon.add_directory({'mode': 'GetTitles', 'url':SunTVUrl,'section': 'tv'}, {'title': 'Sun TV Shows'})
        addon.add_directory({'mode': 'GetTitles', 'url':ThangamUrl,'section': 'tv'}, {'title': 'Thangam TV Shows'})
        addon.add_directory({'mode': 'GetTitles', 'url':thirumathiselvamnUrl,'section': 'tv'}, {'title': 'Thirumathi Selvam TV Shows'})
        addon.add_directory({'mode': 'GetTitles', 'url':ThendralUrl,'section': 'tv'}, {'title': 'Thendral TV Shows'})
        addon.add_directory({'mode': 'GetSearchQuery'},  {'title':  'RajTamil Search'})
        addon.add_directory({'mode': 'GetSearchQueryHD'},  {'title':  'Einthusan Search'})
        
        #addon.add_directory({'mode': 'ResolverSettings'}, {'title':  'Resolver Settings'})
        xbmcplugin.endOfDirectory(int(sys.argv[1]))


def Search(query):
        url = 'http://www.google.com/search?q=%s+site:www.rajtamil.com' % query
        url = url.replace(' ', '+')
        print url
        html = net.http_GET(url).content
        match = re.compile('<h3 class="r"><a href="(.+?)".+?onmousedown=".+?">(.+?)</a>').findall(html)
        for url, title in match:
                title = title.replace('<b>...</b>', '').replace('<em>', '').replace('</em>', '')
                addon.add_directory({'mode': 'GetLinks', 'url': url}, {'title':  title})
        xbmcplugin.endOfDirectory(int(sys.argv[1]))


def SearchHD(query):
        url = 'http://www.einthusan.com/search/?search_query='+ query
        print url
        html = net.http_GET(url).content
        match = re.compile('<li><a href="(.+?)">(.+?)<').findall(html)
        for url,title in match:
                url="http://www.einthusan.com"+url[2:]
                print url
                #addon.add_directory({'mode': 'GetHDLinks', 'url':url}, {'title':  title})
                addon.add_video_item({'url': url, 'mode': 'PlayHDVideo', 'video': "HD Video"}, {'title': title})
        

def RecentHDMovies(recentURL):
        for i in range(1,3):
            recentURL=recentURL+"&page="+str(i)
            html = net.http_GET(recentURL).content
            match = re.compile('<div class="video-object-thumb"><a href="(.+?)"><img.+?src="(.+?)".+?alt="(.+?)"').findall(html)
            for url,img,title in match:
                url="http://www.einthusan.com"+url[2:]
                print url
                addon.add_video_item({'url': url, 'mode': 'PlayHDVideo', 'video': "HD Video"}, {'title': title},img=img)
        
        
        

def GetSearchQuery():
    keyboard = xbmc.Keyboard()
    last_search = addon.load_data('search')
    if not last_search:
        last_search=''
    keyboard.setHeading('Search the site videos')
    keyboard.setDefault(last_search)
    keyboard.doModal()
    if (keyboard.isConfirmed()):
        query = keyboard.getText()
        addon.save_data('search',query)
        Search(query)
    else:
        return

def GetSearchQueryHD():
    keyboard = xbmc.Keyboard()
    last_search = addon.load_data('searchHD')
    if not last_search:
        last_search=''
    keyboard.setHeading('Search the site videos')
    keyboard.setDefault(last_search)
    keyboard.doModal()
    if (keyboard.isConfirmed()):
        query = keyboard.getText()
        addon.save_data('searchHD',query)
        SearchHD(query)
    else:
        return
        

SNAPXML = getXML()


if play:
    #urlresolver.HostedMediaFile(host='dailymotion', media_id=link, title=titlename)
    print "************************************************************Play Video Mode************************************"
    try:
        if mode == 'PlayVideo':
            m=url.split(seperator)
            if(len(m)>1):
                media=urlresolver.HostedMediaFile(host=m[0], media_id=m[1], title=m[2])
                addon.resolve_url(media.resolve())
        elif mode == 'PlayVideoList':
            playlist.clear()
            print '************************************* in Play Video List '
            lines = url.split(lineseperator)
            cnt=0
            for line in lines:
                m=line.split(seperator)
                cnt=cnt+1
                if(len(m)>1):
                    print "M0 "+m[0]+" M1 "+m[1]+" M2 "+m[2]
                    print "******************************************* Playlist item *********** Item No:"+ str(cnt)
                    media=urlresolver.HostedMediaFile(host=m[0], media_id=m[1], title=m[2])
                    if media:
                        link=media.resolve()
                        listItem=xbmcgui.ListItem(link)
                        listItem.setProperty("PlayPath", link)
                        playlist.add(url=link, listitem=listItem)
                        #addon.add_item({'host': m[0], 'media_id': m[1]}, {'title': m[2]},playlist=playlist,resolved=media.resolve())
                    else:
                     addon.resolve_url(line)
            xbmc.Player().play(playlist)
        elif mode == 'PlayHDVideo':
            print "******************************************* Playlist HD Video *********** "
            html = net.http_GET(url).content
            match = re.compile("'file': '(.+?)'").findall(html)
            #if len(match)==1:     
            addon.resolve_url(match[0])
            #if len(match)==2:
            #    addon.resolve_url(match[1])
        else:
            addon.resolve_url(url)
            
    except:
        traceback.print_exc()
        pass
    
if mode == 'main':
    MainMenu()
elif mode == 'GetTitles': 
	GetTitles(url, startPage, numOfPages)
elif mode == 'GetLinks':
	GetLinks(url)
elif mode == 'GetHDLinks':
	GetHDLinks(url)
elif mode == 'GetSearchQuery':
    GetSearchQuery()
elif mode == 'GetSearchQueryHD':
	GetSearchQueryHD()
elif mode == 'Search':
	Search(query)
elif mode == 'SearchHD':
    SearchHD(query)
elif mode=='GetHDTitles':
    RecentHDMovies(url)
    
#elif mode == 'PlayVideo':
#    PlayVideo(url)
#elif mode == 'PlayVideoList':
#	xbmc.Player().play(playlist)	
elif mode == 'ResolverSettings':
    urlresolver.display_settings()
elif mode == 'HindiMenu':
    HindiMenu()
if not play:
    addon.end_of_directory()